import { useRef, useImperativeHandle } from "react";
import PropTypes from 'prop-types'
const toolTipStyle = {
    display: 'none',
    position: 'fixed',
    backgroundColor: '#333',
    color: 'white',
    padding: '8px 12px',
    borderRadius: '4px',
    fontSize: '14px',
    transition: 'opacity 2s',
    zIndex: 1000
}
/* function _useImperativeHandle(ref, factory) {
    ref.current = factory()
} */
function ToolTip({ ref }) {
    const tooltipRef = useRef();
    //通过useImperativeHandle自定义暴露给父组件的内容
    useImperativeHandle(ref, () => ({
        show(event) {
            const x = event.clientX;
            const y = event.clientY;
            tooltipRef.current.style.display = 'block';
            tooltipRef.current.style.opacity = '0';
            tooltipRef.current.style.left = `${x + 10}px`;
            tooltipRef.current.style.top = `${y + 10}px`;
            //触发重排以确保过渡动画生效
            tooltipRef.current.offsetHeight;
            tooltipRef.current.style.opacity = '1';

        },
        hide() {
            tooltipRef.current.style.opacity = '0';
            setTimeout(() => tooltipRef.current.style.display = 'none', 2000);
        }
    }));
    return (
        <div style={toolTipStyle} ref={tooltipRef}>
            这是一个提示框
        </div>
    )
}
ToolTip.propTypes = {
    ref: PropTypes.object.isRequired
}
function App() {
    const tooltipRef = useRef();
    const handleMouseEnter = (event) => {
        tooltipRef.current.show(event);
    }
    const handleMouseLeave = (event) => {
        tooltipRef.current.hide(event);
    }
    return (
        <div>
            <button
                onMouseEnter={handleMouseEnter}
                onMouseLeave={handleMouseLeave}
            >
                鼠标悬停显示提示
            </button>
            <ToolTip ref={tooltipRef} />
        </div>
    )
}
export default App;